package com.bozhong.config.handle;

import com.bozhong.config.parser.*;

import java.io.IOException;
import java.util.Map;

/**
 * @author fupan
 */
public final class NacosDataParserHandler {
	private AbstractNacosDataParser parser;

	private NacosDataParserHandler() {
		this.parser = this.createParser();
	}

	public Map<String, Object> parseNacosData(String data, String extension) throws IOException {
		if (null == this.parser) {
			this.parser = this.createParser();
		}

		return this.parser.parseNacosData(data, extension);
	}

	public boolean checkDataId(String... dataIdAry) {
		StringBuilder stringBuilder = new StringBuilder();
		String[] var3 = dataIdAry;
		int var4 = dataIdAry.length;

		for(int var5 = 0; var5 < var4; ++var5) {
			String dataId = var3[var5];
			int idx = dataId.lastIndexOf(".");
			if (idx > 0 && idx < dataId.length() - 1) {
				String extension = dataId.substring(idx + 1);
				if (this.parser.checkFileExtension(extension)) {
					break;
				}
			}

			stringBuilder.append(dataId).append(",");
		}

		if (stringBuilder.length() > 0) {
			String result = stringBuilder.substring(0, stringBuilder.length() - 1);
			throw new IllegalStateException(AbstractNacosDataParser.getTips(result));
		} else {
			return true;
		}
	}

	private AbstractNacosDataParser createParser() {
		return (new NacosDataPropertiesParser()).addNextParser(new NacosDataYamlParser()).addNextParser(new NacosDataXmlParser()).addNextParser(new NacosDataJsonParser());
	}

	public static NacosDataParserHandler getInstance() {
		return NacosDataParserHandler.ParserHandler.HANDLER;
	}

	private static class ParserHandler {
		private static final NacosDataParserHandler HANDLER = new NacosDataParserHandler();

		private ParserHandler() {
		}
	}
}
